Objective-C Runtime的Associated Objects在swift中的使用

最佳实践

matt大神在这里给出了一个最佳实践:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
extension UIViewController {
private struct AssociatedKeys {
static var DescriptiveName = "nsh_DescriptiveName"
}

var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)
)
}
}
}
}

一个利用runtime添加角标的例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//用于显示小角标
extension UIView {

//设置一个用于存放Objc-Runtime key 的结构体
//参考资料http://nshipster.com/swift-objc-runtime/
private struct AssociatedKeys {
static var NumLabelKey = "Cooper_NumLaebel"
}

func showCornerStatus(badgeNumber:Int,rateX:CGFloat,rateY:CGFloat){
self.removeCornerStatus()
if badgeNumber == 0 {
return
}

var labelWidth: CGFloat = 20
var numLabel = UILabel(frame: CGRectMake(0, 0, labelWidth, labelWidth))
var settingCenter = CGPointZero

settingCenter.x = self.frame.width * rateX
settingCenter.y = self.frame.width * rateY

numLabel.center = settingCenter
numLabel.layer.cornerRadius = labelWidth/2
numLabel.clipsToBounds = true
numLabel.backgroundColor = UIColor.redColor()
numLabel.textColor = UIColor.whiteColor()
numLabel.textAlignment = NSTextAlignment.Center
numLabel.font = UIFont(name: "FZLanTingHeiS-R-GB", size: 10) ?? UIFont.systemFontOfSize(10)
numLabel.text = badgeNumber > 99 ? "..." : "\(badgeNumber)"

//设置关联变量
objc_setAssociatedObject(self,&AssociatedKeys.NumLabelKey, numLabel, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))

self.addSubview(numLabel)

}

func removeCornerStatus(){
var numLabel = objc_getAssociatedObject(self, &AssociatedKeys.NumLabelKey) as? UIView
numLabel?.removeFromSuperview()
}
}

用法:

1
2
var btn = UIButton()
btn.showCornerStatus(8, rateX: 0.7, rateY: 0.12)

效果:
效果

参考资料

swift-objc-runtime